<!DOCTYPE html>
<html lang="zh-CN" color-mode=light>


<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>将位图嵌入SVG：一个简单的Python脚本 - 树朾的开源技术分享</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  <meta name="keywords" content="开源, 分享">
  <meta name="description" content="在现代网页设计中，SVG（Scalable Vecto...">
  <meta name="author" content="scwang90">
  <link rel="icon" href="/images/icons/favicon.ico">
  
  
  
  
  

  
<link rel="stylesheet" href="/css/style.css">


  
    
<link rel="stylesheet" href="https://at.alicdn.com/t/font_1445822_p6ry5n7lrr.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      loading: {
        gif: '/images/theme/loading.gif',
        lottie: ''
      },
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: {
          gif: '/images/theme/loading.gif',
          lottie: ''
        }
      },
      donate: {
        enable: false,
        alipay: '/images/donate/pay_alipay.jpg',
        wechat: '/images/donate/pay_wxpay.jpg',
        tencent: '/images/donate/pay_tencent.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          typing: true,
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: true,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        type: 'default'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      },
      search: {
        enable: false,
        path: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 6.2.0"></head>

<body class="lock-screen">
  <div class="loading" id="loading"></div>
  
    


  <nav class="navbar">
    <div class="left">
      
        <i class="iconfont iconhome j-navbar-back-home"></i>
      
      
        <i class="iconfont iconqrcode j-navbar-qrcode"></i>
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
      
    </div>
    <div class="center">将位图嵌入SVG：一个简单的Python脚本</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
      <div id="qrcode-navbar"></div>
    
  </nav>

  
  

<nav class="menu">
  <div class="menu-container">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/galleries/ " class="underline "> 摄影</a>
      </li><li class="menu-item">
        <a href="/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://github.com/scwang90">scwang90</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p> <p><a target="_blank" href="http://beian.miit.gov.cn/"><span>黔ICP备2021004317号-1</span></a><span>  |  </span><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img class="lazyload" data-original="/images/icons/icon-filing.png" src="https://www.beian.gov.cn/img/new/gongan.png"/> <span> 贵公网安备 52010202002539号</span></a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    
      <div class="row container container-lg">
        <div class="col-xl-2"></div>
        <div class="col-xl-8"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/images/theme/post-image.jpg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">将位图嵌入SVG：一个简单的Python脚本</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>十二月 10, 2024</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>3055</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content article-entry">
        
          
            <p>在现代网页设计中，SVG（Scalable Vector Graphics）因其可缩放性和灵活性而变得越来越流行。SVG不仅可以包含矢量图形，还可以嵌入位图图像。这使得设计师和开发者能够在一个文件中结合矢量图形的清晰度和位图图像的丰富细节。本文将介绍如何使用Python脚本将PNG和JPG位图图像嵌入SVG文件中。</p>
          
        
        <h2 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h2><p>在开始之前，请确保您的开发环境中安装了Python和Pillow库（PIL的更新版）。Pillow库允许Python处理图像文件。如果尚未安装Pillow，可以通过pip安装：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install Pillow</span><br></pre></td></tr></table></figure>

<h2 id="Python脚本解析"><a href="#Python脚本解析" class="headerlink" title="Python脚本解析"></a>Python脚本解析</h2><p>下面是一个Python脚本，它遍历当前目录下的所有PNG和JPG文件，并将它们转换为SVG格式，同时将位图图像以Base64编码的形式嵌入SVG中。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image</span><br><span class="line"><span class="keyword">import</span> base64</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将图片文件转换为Base64编码的字符串</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">image_to_base64</span>(<span class="params">image_path</span>):</span><br><span class="line">    <span class="keyword">with</span> <span class="built_in">open</span>(image_path, <span class="string">&quot;rb&quot;</span>) <span class="keyword">as</span> image_file:</span><br><span class="line">        encoded_string = base64.b64encode(image_file.read()).decode(<span class="string">&#x27;utf-8&#x27;</span>)</span><br><span class="line">    <span class="keyword">return</span> encoded_string</span><br><span class="line"></span><br><span class="line"><span class="comment"># 根据Base64编码的图片数据创建SVG文件</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">create_svg_with_base64</span>(<span class="params">image_base64, output_path, size, filename</span>):</span><br><span class="line">    w, h = size</span><br><span class="line">    <span class="built_in">id</span> = os.path.basename(filename)</span><br><span class="line">    svg_template = <span class="string">f&#x27;&#x27;&#x27;&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; fill=&quot;none&quot; version=&quot;1.1&quot;</span></span><br><span class="line"><span class="string">     width=&quot;<span class="subst">&#123;w&#125;</span>&quot; height=&quot;<span class="subst">&#123;h&#125;</span>&quot; viewBox=&quot;0 0 <span class="subst">&#123;w&#125;</span> <span class="subst">&#123;h&#125;</span>&quot;&gt;</span></span><br><span class="line"><span class="string">    &lt;defs&gt;</span></span><br><span class="line"><span class="string">        &lt;pattern x=&quot;0&quot; y=&quot;0&quot; width=&quot;<span class="subst">&#123;w&#125;</span>&quot; height=&quot;<span class="subst">&#123;h&#125;</span>&quot; patternUnits=&quot;userSpaceOnUse&quot; id=&quot;<span class="subst">&#123;<span class="built_in">id</span>&#125;</span>&quot;&gt;</span></span><br><span class="line"><span class="string">            &lt;image x=&quot;0&quot; y=&quot;0&quot; width=&quot;<span class="subst">&#123;w&#125;</span>&quot; height=&quot;<span class="subst">&#123;h&#125;</span>&quot; xlink:href=&quot;data:image/<span class="subst">&#123;os.path.splitext(filename)[<span class="number">1</span>].upper()&#125;</span>;base64,<span class="subst">&#123;image_base64&#125;</span>&quot;/&gt;</span></span><br><span class="line"><span class="string">        &lt;/pattern&gt;</span></span><br><span class="line"><span class="string">    &lt;/defs&gt;</span></span><br><span class="line"><span class="string">    &lt;g&gt;</span></span><br><span class="line"><span class="string">        &lt;rect x=&quot;0&quot; y=&quot;0&quot; width=&quot;<span class="subst">&#123;w&#125;</span>&quot; height=&quot;<span class="subst">&#123;h&#125;</span>&quot; rx=&quot;0&quot; fill=&quot;url(#<span class="subst">&#123;<span class="built_in">id</span>&#125;</span>)&quot; fill-opacity=&quot;1&quot;/&gt;</span></span><br><span class="line"><span class="string">    &lt;/g&gt;</span></span><br><span class="line"><span class="string">&lt;/svg&gt;&#x27;&#x27;&#x27;</span></span><br><span class="line">    <span class="keyword">with</span> <span class="built_in">open</span>(output_path, <span class="string">&#x27;w&#x27;</span>) <span class="keyword">as</span> svg_file:</span><br><span class="line">        svg_file.write(svg_template)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将JPG和PNG图片转换为SVG格式</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">convert_images_to_svg</span>():</span><br><span class="line">    <span class="keyword">for</span> filename <span class="keyword">in</span> os.listdir(<span class="string">&#x27;.&#x27;</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;filename&#x27;</span>, filename)</span><br><span class="line">        <span class="keyword">if</span> filename.lower().endswith((<span class="string">&quot;.png&quot;</span>, <span class="string">&quot;.jpg&quot;</span>)):</span><br><span class="line">            image_path = filename</span><br><span class="line">            <span class="keyword">try</span>:</span><br><span class="line">                base64_data = image_to_base64(image_path)</span><br><span class="line">                output_path = <span class="string">f&quot;service-<span class="subst">&#123;os.path.splitext(image_path)[<span class="number">0</span>]&#125;</span>.svg&quot;</span></span><br><span class="line">                <span class="keyword">with</span> Image.<span class="built_in">open</span>(image_path) <span class="keyword">as</span> img:</span><br><span class="line">                    create_svg_with_base64(base64_data, output_path, img.size, filename)</span><br><span class="line">                    <span class="built_in">print</span>(<span class="string">f&quot;Converted <span class="subst">&#123;image_path&#125;</span> to <span class="subst">&#123;output_path&#125;</span>&quot;</span>)</span><br><span class="line">            <span class="keyword">except</span> IOError:</span><br><span class="line">                <span class="built_in">print</span>(<span class="string">f&quot;Failed to open <span class="subst">&#123;image_path&#125;</span> as an image.&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 调用函数</span></span><br><span class="line">convert_images_to_svg()</span><br></pre></td></tr></table></figure>

<h2 id="脚本工作流程"><a href="#脚本工作流程" class="headerlink" title="脚本工作流程"></a>脚本工作流程</h2><ol>
<li><strong>导入必要的库</strong>：脚本开始时导入了<code>os</code>、<code>PIL.Image</code>和<code>base64</code>库。</li>
<li><strong>定义<code>image_to_base64</code>函数</strong>：这个函数打开一个图像文件，读取其内容，并使用base64进行编码。</li>
<li><strong>定义<code>create_svg_with_base64</code>函数</strong>：该函数接受Base64编码的图像数据，并创建一个包含该图像的SVG文件。</li>
<li><strong>定义<code>convert_images_to_svg</code>函数</strong>：这个函数遍历当前目录下的所有文件，对于每个PNG或JPG文件，它将调用上述两个函数来生成SVG文件。</li>
<li><strong>执行转换</strong>：最后，脚本调用<code>convert_images_to_svg</code>函数来执行转换。</li>
</ol>
<h2 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h2><p>通过这个简单的Python脚本，我们可以轻松地将位图图像嵌入SVG文件中，这不仅提高了设计的灵活性，还可能优化网页的性能。这种方法特别适合需要在SVG中使用复杂位图图像的场景，例如图标、背景图像或复杂的设计元素。希望这篇文章能帮助你更好地理解和实现位图嵌入SVG的技术。</p>

      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>scwang90</li>
    <li><strong>本文链接：</strong><a href="https://blog.scwang90.cn/2024/12/10/python-image-to-svg/index.html" title="https:&#x2F;&#x2F;blog.scwang90.cn&#x2F;2024&#x2F;12&#x2F;10&#x2F;python-image-to-svg&#x2F;index.html">https:&#x2F;&#x2F;blog.scwang90.cn&#x2F;2024&#x2F;12&#x2F;10&#x2F;python-image-to-svg&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本分享所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/svg/" rel="tag">svg</a></li></ul> 

        
  <nav class="nav">
    <a href="/2024/12/13/breakthrough-echarts/"><i class="iconfont iconleft"></i>Echarts 难点攻克</a>
    <a href="/2024/11/18/vue-stream-api/">fetch EventSource 请求，vue2 项目 webpack 没有流式输出<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
        <div class="col-xl-2">
          
            
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C"><span class="toc-text">准备工作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Python%E8%84%9A%E6%9C%AC%E8%A7%A3%E6%9E%90"><span class="toc-text">Python脚本解析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%84%9A%E6%9C%AC%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="toc-text">脚本工作流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%93%E8%AE%BA"><span class="toc-text">结论</span></a></li></ol>
  </aside>

          
        </div>
      </div>
    
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=283371828 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="javascript:; "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#09BB07'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconwechat-fill "></i>
      </a><a 
        href="https://github.com/scwang90 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="mailto:scwang90@hotmail.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=#FF3B00" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail"></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://github.com/scwang90">scwang90</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p> <p><a target="_blank" href="http://beian.miit.gov.cn/"><span>黔ICP备2021004317号-1</span></a><span>  |  </span><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img class="lazyload" data-original="/images/icons/icon-filing.png" src="https://www.beian.gov.cn/img/new/gongan.png"/> <span> 贵公网安备 52010202002539号</span></a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
  
    
<script src="/js/color-mode.js"></script>

  
  
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>





  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>






  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>




<script src="/js/utils.js"></script>
<script src="/js/script.js"></script>







  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>